using GroupSix.Domain.Entity.App;
using GroupSix.Domain.Repositories;
using GroupSix.Domain.common;
using Microsoft.EntityFrameworkCore;

namespace GroupSix.Infrastructure.Reposoitories;

/// <summary>
/// 角色仓库实现
/// </summary>
public class RoleRepository : EfRepository<GsRole>, IRoleRepository
{
    public RoleRepository(GroupSix.Infrastructure.Data.GroupSixDbContext context) : base(context)
    {
    }

    /// <summary>
    /// 检查角色名称是否存在
    /// </summary>
    public async Task<bool> IsNameExistsAsync(string name, Guid? excludeId = null)
    {
        var query = _tb.Where(r => r.Name == name && !r.IsDeleted);
        
        if (excludeId.HasValue)
        {
            query = query.Where(r => r.Id != excludeId.Value);
        }

        return await query.AnyAsync();
    }

    /// <summary>
    /// 根据名称获取角色
    /// </summary>
    public async Task<GsRole?> GetByNameAsync(string name)
    {
        return await _tb.FirstOrDefaultAsync(r => r.Name == name && !r.IsDeleted);
    }

    /// <summary>
    /// 分页查询角色列表
    /// </summary>
    public async Task<PageResult<GsRole>> GetPagedAsync(PageRequest request, string? name = null)
    {
        var query = _tb.Where(r => !r.IsDeleted);

        // 按名称搜索
        if (!string.IsNullOrEmpty(name))
        {
            query = query.Where(r => r.Name.Contains(name));
        }

        var totalCount = await query.CountAsync();

        var items = await query
            .OrderBy(r => r.CreatedAt)
            .Skip((request.PageIndex - 1) * request.PageSize)
            .Take(request.PageSize)
            .ToListAsync();

        return new PageResult<GsRole>
        {
            Items = items,
            TotalCount = totalCount,
            PageIndex = request.PageIndex,
            PageSize = request.PageSize
        };
    }

    /// <summary>
    /// 获取角色及其关联的菜单
    /// </summary>
    public async Task<GsRole?> GetWithMenusAsync(Guid id)
    {
        return await _tb
            .Include(r => r.GsRoleMenus)
                .ThenInclude(rm => rm.Menu)
            .FirstOrDefaultAsync(r => r.Id == id && !r.IsDeleted);
    }

    /// <summary>
    /// 检查角色是否被用户使用
    /// </summary>
    public async Task<bool> IsUsedByUsersAsync(Guid roleId)
    {
        return await _db.Set<GsUserRole>()
            .AnyAsync(ur => ur.RoleId == roleId && !ur.IsDeleted);
    }

    /// <summary>
    /// 获取角色的用户数量
    /// </summary>
    public async Task<int> GetUserCountAsync(Guid roleId)
    {
        return await _db.Set<GsUserRole>()
            .CountAsync(ur => ur.RoleId == roleId && !ur.IsDeleted);
    }

    /// <summary>
    /// 批量删除角色菜单关联
    /// </summary>
    public async Task<int> DeleteRoleMenusAsync(Guid roleId)
    {
        var roleMenus = await _db.Set<GsRoleMenu>()
            .Where(rm => rm.RoleId == roleId)
            .ToListAsync();

        _db.Set<GsRoleMenu>().RemoveRange(roleMenus);
        await _db.SaveChangesAsync();
        return roleMenus.Count;
    }

    /// <summary>
    /// 批量添加角色菜单关联
    /// </summary>
    public async Task<int> AddRoleMenusAsync(IEnumerable<GsRoleMenu> roleMenus)
    {
        await _db.Set<GsRoleMenu>().AddRangeAsync(roleMenus);
        await _db.SaveChangesAsync();
        return roleMenus.Count();
    }
    
    /// <summary>
    /// 获取角色菜单关联
    /// </summary>
    public async Task<List<GsRoleMenu>> GetRoleMenusAsync(List<Guid> roleIds)
    {
        return await _db.Set<GsRoleMenu>()
            .Include(rm => rm.Menu)
            .Where(rm => roleIds.Contains(rm.RoleId) && !rm.IsDeleted)
            .ToListAsync();
    }
} 